package com.sky.controller.user;

import com.sky.Result.Result;
import com.sky.constant.JwtClaimsConstant;
import com.sky.model.dto.UserLoginDTO;
import com.sky.model.entity.User;
import com.sky.model.vo.UserLoginVO;
import com.sky.model.vo.UserVO;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController("userUserController")
@Slf4j
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户注册
     * @param userLoginDTO
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户注册：username:{},password:{}", userLoginDTO.getUsername(), userLoginDTO.getPassword());
        userService.register(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        return Result.success();
    }

    /**
     * 用户登录
     * @param userLoginDTO
     */
    @PostMapping("/login")
    public Result<UserLoginVO>login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：userLoginDTO{}",userLoginDTO );
        User user=userService.login(userLoginDTO.getUsername(), userLoginDTO.getPassword());

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //创建userLoginvo对象
        UserLoginVO userLoginVO=UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**修改个人信息
     * @param userDTO
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody User userDTO) {
        log.info("修改个人信息：userDTO{}", userDTO);
        userService.update(userDTO);
        return Result.success();
    }
    /**
     * 返回用户信息
     */
    @PostMapping("/info")
    public Result<UserVO> info() {
        log.info("返回用户信息");
        UserVO user = userService.info();
        return Result.success(user);
    }
}
